package com.example.everying.utils;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Slf4j
@Component
public class AliGreenModerationUtil {

    @Value("${aliyun.green.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.green.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.green.regionId}")
    private String regionId;

    @Value("${aliyun.green.endpoint}")
    private String endpoint;

    @Value("${aliyun.green.read-timeout:6000}")
    private int readTimeout;

    @Value("${aliyun.green.connect-timeout:3000}")
    private int connectTimeout;

    private Client client;

    @PostConstruct
    public void init() throws Exception {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        config.setRegionId(regionId);
        config.setEndpoint(endpoint);
        config.setReadTimeout(readTimeout);
        config.setConnectTimeout(connectTimeout);
        this.client = new Client(config);
    }

    /**
     * 文本内容审核
     *
     * @param content 待审核的文本内容
     * @return 审核结果
     */
    public TextModerationResult moderateText(String content) {
        TextModerationResult result = new TextModerationResult();

        try {
            JSONObject serviceParameters = new JSONObject();
            serviceParameters.put("content", content);

            TextModerationPlusRequest request = new TextModerationPlusRequest();
            request.setService("comment_detection_pro");
            request.setServiceParameters(serviceParameters.toJSONString());

            TextModerationPlusResponse response = client.textModerationPlus(request);

            result.setStatusCode(response.getStatusCode());

            if (response.getStatusCode() == 200) {
                TextModerationPlusResponseBody body = response.getBody();
                result.setRequestId(body.getRequestId());
                result.setCode(body.getCode());
                result.setMessage(body.getMessage());

                if (200 == body.getCode()) {
                    result.setData(body.getData());
                    result.setSuccess(true);
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Moderation  failed: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 判断文本是否包含违禁词
     *
     * @param text 待检测的文本内容
     * @return true-包含违禁词 false-不包含违禁词或审核失败
     */
    public boolean containsProhibitedWords(String text) {
        // 1. 调用审核接口
        AliGreenModerationUtil.TextModerationResult result = moderateText(text);

        // 2. 基础校验
        if (!result.isSuccess() || result.getData() == null) {
            // 审核失败时，可以根据业务需求返回true或false
            // 这里选择保守策略，返回true表示可能存在风险
            return true;
        }

        // 3. 根据riskLevel和advice判断
        TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();

        // 高风险直接判定为违禁
        if ("high".equalsIgnoreCase(data.getRiskLevel())) {
            return true;
        }
        return false;
//        // 4. 检查是否有违禁词数组（labels）
//        return data.getResult() != null && !data.getResult().isEmpty();
    }

    /**
     * 图片URL内容安全检测
     *
     * @param imageUrl 公网可访问的图片URL
     * @return 检测结果
     */
    public ImageModerationResult checkImage(String imageUrl) {
        return checkImage(imageUrl, UUID.randomUUID().toString());
    }

    /**
     * 图片URL内容安全检测
     *
     * @param imageUrl 公网可访问的图片URL
     * @param dataId   自定义数据ID（用于关联业务）
     * @return 检测结果
     */
    public ImageModerationResult checkImage(String imageUrl, String dataId) {
        ImageModerationResult result = new ImageModerationResult();

        try {
            // 构造请求参数
            Map<String, String> serviceParameters = new HashMap<>();
            serviceParameters.put("imageUrl", imageUrl);
            serviceParameters.put("dataId", dataId);

            ImageModerationRequest request = new ImageModerationRequest();
            request.setService("baselineCheck");
            request.setServiceParameters(JSON.toJSONString(serviceParameters));

            // 执行检测
            ImageModerationResponse response = client.imageModerationWithOptions(request, new RuntimeOptions());
            result.setRawResponse(response);

            if (response != null) {
                result.setStatusCode(response.getStatusCode());

                if (response.getStatusCode() == 200) {
                    ImageModerationResponseBody body = response.getBody();
                    result.setRequestId(body.getRequestId());
                    result.setCode(body.getCode());
                    result.setMessage(body.getMsg());

                    if (body.getCode() == 200 && body.getData() != null) {
                        result.setDataId(body.getData().getDataId());
                        result.setResults(body.getData().getResult());
                        result.setSuccess(true);
                    }
                }
            }
        } catch (Exception e) {
            log.error(" 图片内容安全检测异常", e);
            result.setSuccess(false);
            result.setMessage(" 检测服务异常: " + e.getMessage());
        }

        return result;
    }

  /**
 * 判断图片是否包含违规内容
 *
 * @param imageUrl 待检测的图片URL（公网可访问）
 * @return true-包含违规内容 false-不包含违规内容或检测失败
 */
public boolean containsProhibitedContent(String imageUrl) {
    long startTime = System.currentTimeMillis();
    log.info("开始图片内容安全检测，URL: {}", imageUrl);

    try {
        // 1. 调用图片审核接口
        long checkStartTime = System.currentTimeMillis();
        ImageModerationResult result = checkImage(imageUrl);
        long checkEndTime = System.currentTimeMillis();
        long checkDuration = checkEndTime - checkStartTime;
        log.info("图片审核接口调用完成，耗时: {} ms", checkDuration);
        log.debug("图片检测原始结果: {}", result);

        // 2. 基础校验
        if (!result.isSuccess() || result.getRawResponse() == null) {
            log.warn("图片检测服务异常 - 检测失败: {}", result.getMessage());
            // 检测失败时，保守策略返回true表示可能存在风险
            long endTime = System.currentTimeMillis();
            long totalDuration = endTime - startTime;
            log.info("图片内容安全检测完成(失败)，总耗时: {} ms", totalDuration);
            return true;
        }

        // 3. 获取检测数据
        ImageModerationResponse response = result.getRawResponse();

        // 4. HTTP状态码检查
        if (response.getStatusCode() != 200) {
            log.warn("图片检测服务异常 - HTTP状态码: {}", response.getStatusCode());
            long endTime = System.currentTimeMillis();
            long totalDuration = endTime - startTime;
            log.info("图片内容安全检测完成(失败)，总耗时: {} ms", totalDuration);
            return true;
        }

        // 5. 业务状态码检查
        ImageModerationResponseBody body = response.getBody();
        if (body == null || body.getCode() != 200) {
            log.warn("图片检测业务异常 - 业务码: {}, 消息: {}",
                    (body != null ? body.getCode() : "null"),
                    (body != null ? body.getMsg() : "null"));
            long endTime = System.currentTimeMillis();
            long totalDuration = endTime - startTime;
            log.info("图片内容安全检测完成(失败)，总耗时: {} ms", totalDuration);
            return true;
        }

        // 6. 检测结果数据检查
        ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
        if (data == null || data.getResult() == null) {
            log.info("图片检测结果数据为空，视为安全内容");
            long endTime = System.currentTimeMillis();
            long totalDuration = endTime - startTime;
            log.info("图片内容安全检测完成(通过)，总耗时: {} ms", totalDuration);
            return false;
        }

        // 高风险直接判定为违禁
        boolean isProhibited = "high".equalsIgnoreCase(data.getRiskLevel());
        long endTime = System.currentTimeMillis();
        long totalDuration = endTime - startTime;
        log.info("图片内容安全检测完成，风险等级: {}, 总耗时: {} ms", data.getRiskLevel(), totalDuration);
        return isProhibited;

    } catch (Exception e) {
        long endTime = System.currentTimeMillis();
        long totalDuration = endTime - startTime;
        log.error("图片内容安全检测异常，总耗时: {} ms", totalDuration, e);
        // 出现异常时保守处理，返回true表示可能存在风险
        return true;
    }
}


    @Data
    public static class TextModerationResult {
        // 保持与之前相同的实现
        private boolean success;
        private int statusCode;
        private String requestId;
        private Integer code;
        private String message;
        private TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data;

        // Getters and Setters...
        @Override
        public String toString() {
            return JSON.toJSONString(this, true);
        }
    }

    /**
     * 图片检测结果封装
     */
    @Data
    public static class ImageModerationResult {
        private boolean success;
        private int statusCode;
        private String requestId;
        private Integer code;
        private String message;
        private String dataId;
        private List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> results;
        private ImageModerationResponse rawResponse;

        /**
         * 是否包含风险内容
         */
        public boolean hasRisk() {
            if (!success || results == null) return false;
            return results.stream().anyMatch(r -> r.getConfidence() > 80); // 置信度大于80%视为有效风险
        }

        /**
         * 获取最高风险等级
         */
        public String getHighestRiskLevel() {
            if (!success || results == null) return "pass";
            return results.stream()
                    .max(Comparator.comparing(ImageModerationResponseBody.ImageModerationResponseBodyDataResult::getConfidence))
                    .map(ImageModerationResponseBody.ImageModerationResponseBodyDataResult::getLabel)
                    .orElse("pass");
        }

        @Override
        public String toString() {
            return JSON.toJSONString(this, true);
        }
    }

    public static void main(String[] args) {
        try {
            // 1. 创建测试实例 (注意：实际使用时应该通过Spring注入)
            AliGreenModerationUtil util = new AliGreenModerationUtil();

            // 2. 手动设置配置（因为不在Spring环境中）
            util.accessKeyId = "LTAI5t8SaRP7na1rPDp2HRjp"; // 替换为实际值
            util.accessKeySecret = "5pWa2XgR69iPAFTTknSFfVjD4XqQ13"; // 替换为实际值
            util.regionId = "cn-beijing";
            util.endpoint = "green-cip.cn-beijing.aliyuncs.com";
            util.readTimeout = 6000;
            util.connectTimeout = 3000;

            // 3. 手动初始化（模拟@PostConstruct）
            util.init();

            // 4. 测试文本
            String[] testTexts = {
                    "有没有六点以后从容东回安新三台的捎上我，价格私聊，有宠物！！！",
                    "旅游攻略"
            };

            // 5. 测试每个文本
            for (String text : testTexts) {
                System.out.println("\n 测试文本: " + text);

                // 完整审核结果
                AliGreenModerationUtil.TextModerationResult result = util.moderateText(text);
                System.out.println(" 完整审核结果:");
                System.out.println(result);

                // 简单判断
                boolean hasProhibited = util.containsProhibitedWords(text);
                System.out.println(" 是否包含违禁词: " + hasProhibited);

                // 风险等级
                if (result.getData() != null) {
                    System.out.println(" 风险等级: " + result.getData().getRiskLevel());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
